package leetcode.L105;

import java.util.HashMap;
import java.util.Map;

class Solution {
    public Map<Integer, Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        //把中序遍历的入map
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return myBuildTree(preorder, inorder, 0, preorder.length - 1, 0, preorder.length - 1);
    }

    //递归简历二叉树
    public TreeNode myBuildTree(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
        if (preStart > preEnd) {
            return null;
        }
        //建立根节点
        TreeNode node = new TreeNode(preorder[preStart]);
        //节点不重复，找到对应为止
        int pos = map.get(preorder[preStart]);
        //左子在左边，右子在右边
        int leftLen = pos - inStart;
        node.left=myBuildTree(preorder,inorder,preStart+1,preStart+leftLen,inStart,pos-1);
        node.right=myBuildTree(preorder,inorder,preStart+leftLen+1,preEnd,pos+1,inEnd);
        return node;
    }
}